import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/mall_app/my_gas/logic.dart';
import 'package:yp/services/api.dart';

import 'state.dart';

class GasAddLogic extends GetxController {
  final GasAddState state = GasAddState();

  @override
  void onInit() {
    super.onInit();

    var params = Get.arguments ?? {};
    state.from = params['from'];

    state.gasNumberController = TextEditingController();
    state.gasNumberFocusNode = FocusNode();

    state.whetherBindBool = false;
    print('state.gasString = ${Get.parameters['gasStr']}');
    state.gasString = Get?.parameters['gasStr'] ?? '';
    print('state.gasString = ${state.gasString}');

    update();

    state.gasNumberController.addListener(() {
      print('=========== value: ${state.gasNumberController.text}');
      state.hasInput.value = state.gasNumberController.text.isNotEmpty;
    });

    String gasTag = SpUtil.getString("gasTag", defValue: "");

    if (gasTag.isNotEmpty) {
      state.tagList[2] = gasTag;
    }
  }

  // bindingNaturalGas
  void bindingNaturalGas({
    String gasCode,
  }) {
    var params = {
      'gas_code': gasCode,
      'gas_association': state.selectedIndex < 10
          ? state.tagList[state.selectedIndex]
          : '',
      'access_token': SpUtil.getString('token'),
    };
    print(params);
    Api.bindingNaturalGas(params).listen((event) {
      print(' 绑定天然气  返回数据   event = $event');
      if (event['code'] == 0) {
        state.gasNumberController.text = '';
        state.gasString = gasCode;
        toast('绑定成功');
        MyGasLogic myGasLogic = Get.find<MyGasLogic>();
        myGasLogic.getNaturalGasList();
        Get.back(result: {'gasCode': gasCode, 'from': 'point_exchange'});
      } else {
        state.gasString = '';
        toast('${event['message']}');
      }
      update();
    });
  }

  void onWhetherBindClick() {
    if (state.gasNumberController.text.length > 0) {
      state.whetherBindBool = true;
    } else {
      state.whetherBindBool = false;
    }
    update();
  }

  @override
  void onClose() {
    super.onClose();

    print('GasAddLogic: 我走了');
  }


  void chooseClick(int index) {
    state.chooseIndex = index;
    update();
  }
}
